<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of QQlogin
 *
 * @author Administrator
 */
class QQlogin extends ThirdPartyLogin{
    //put your code here
    const GET_AUTH_CODE_URL = "https://graph.qq.com/oauth2.0/authorize";
    const GET_ACCESS_TOKEN_URL = "https://graph.qq.com/oauth2.0/token";
    const GET_OPENID_URL = "https://graph.qq.com/oauth2.0/me";
    private $settingLogic;
    private $app_id;
    private $app_key;
    private $redirect_uri;
    private $scope;
    private $state;
    
    public function __construct() {
        parent::__construct();
        $this->settingLogic=  $this->load("setting");
        $db=$this->settingLogic->get_one("option_value", "option_key='QQ_APP_ID'");
        $db2=$this->settingLogic->get_one("option_value", "option_key='QQ_APP_KEY'");
        $db3=$this->settingLogic->get_one("option_value", "option_key='QQ_REDIRECT_URI'");
        $this->app_id=$db["option_value"];
        $this->app_key=$db2["option_value"];
        $this->redirect_uri=  urlencode($db3["option_value"]);
        $this->scope="get_user_info";
       
        
    }
    //qq快捷登录
    public function login(){
         $this->state="qqlogin".uniqid(rand(), TRUE);
         $_SESSION["QQ_state"]=  $this->state;
         $url= self::GET_AUTH_CODE_URL."?response_type=code&client_id={$this->app_id}&redirect_uri={$this->redirect_uri}&state={$this->state}&scope={$this->scope}";
         header("Location:{$url}");
    }
    //回调地址
    public function callback(){
        if($_SESSION["QQ_state"]!=$_GET['state']){
            $this->showError("30001");
        }
         $keysArr = array(
            "grant_type" => "authorization_code",
            "client_id" => $this->app_id,
            "redirect_uri" =>  $this->redirect_uri,
            "client_secret" =>  $this->app_key,
            "code" => $_GET['code']
        );
       $url=  $this->combineURL(self::GET_ACCESS_TOKEN_URL, $keysArr);
       $response=  Common::Get_Contents($url);
       if(strpos($response, "callback") !== false){

            $lpos = strpos($response, "(");
            $rpos = strrpos($response, ")");
            $response  = substr($response, $lpos + 1, $rpos - $lpos -1);
            $msg = json_decode($response);

            if(isset($msg->error)){
                $this->showError($msg->error, $msg->error_description);
            }
        }
        
        $params = array();
        parse_str($response, $params);
        $_SESSION["qq_access_token"]=$params["access_token"];
        $this->get_openid();
        $user=$this->get_user_info();
        $this->SaveToTenant($user);
        echo "<script>if(window.opener){window.opener.location.href='".Common::RewriteUrl("Tenantadmin","index")."';window.close();}else{window.location.href='".Common::RewriteUrl("Tenantadmin","index")."';}</script>";
    }
    //获得用户唯一的openid于qq一一对应
    public function get_openid(){

        //-------请求参数列表
        $keysArr = array(
            "access_token" => $_SESSION["qq_access_token"]
        );

        $graph_url = $this->combineURL(self::GET_OPENID_URL, $keysArr);
        $response =  Common::get_contents($graph_url);

        //--------检测错误是否发生
        if(strpos($response, "callback") !== false){

            $lpos = strpos($response, "(");
            $rpos = strrpos($response, ")");
            $response = substr($response, $lpos + 1, $rpos - $lpos -1);
        }

        $user = json_decode($response);
        if(isset($user->error)){
            $this->showError($user->error, $user->error_description);
        }

        //------记录openid
        $_SESSION["qq_openid"]=$user->openid;
        
    }
    private function get_user_info(){
        $url="https://graph.qq.com/user/get_user_info";
        $keysArr = array(
            "access_token" => $_SESSION["qq_access_token"],
            "oauth_consumer_key"=>  $this->app_id,
            "openid"=>$_SESSION["qq_openid"]
        );
        $url=$this->combineURL($url, $keysArr);
        $response= json_decode(Common::Get_Contents($url));
        return $response;
    }
    //把qq资料当成租户信息保存到租户表
    public function SaveToTenant($user){
        $tenantLogic=  $this->load("tenant");
        $cityLogic=  $this->load("city");
        $provinceLogic=  $this->load("province");
        if($user->ret>=0){
            $password=  md5($_SESSION["qq_openid"]);
            $exist=$tenantLogic->get_one("*", "((user_name='{$_SESSION["qq_openid"]}' and password='{$password}') or third_uid='{$_SESSION["qq_openid"]}') and status=1");
            if(!$exist){
                
             $w=PinYin::cn_explode(Common::strEscape($user->nickname));
             $zimu="";
             foreach ($w as $v){
                    $zimu.= PinYin::to_first($v) ;
             }
                
                 $tenantinfo=array(
                     "base_name"=>$user->nickname,
                     "user_name"=>$_SESSION["qq_openid"],
                     "password"=>$password,
                     "sex"=>$user->nickname=="女"?2:1,
                     "create_time"=>  time(),
                     "last_login_ip"=>  Common::getIp(),
                     "city"=>$user->city,
                     "year"=>$user->year,
                     "province"=>$user->province,
                     "last_login_time"=>  time(),
                     "status"=>  1,
                     "is_third"=>1,
                     "sx"=>$zimu,
                     "third_uid"=>$_SESSION["qq_openid"],
                     "pinyin"=>  PinYin::utf8_to(Common::strEscape($user->nickname))
                 );   
                 if(isset($user->province)){
                      $province=  $provinceLogic->get_one("*", "province like '{$user->province}%'");
                      if($province)
                      $tenantinfo["province_id"]=$province["id"];
                 }
                 if(isset($user->city)){
                      $city=  $cityLogic->get_one("*", "city like '{$user->city}%'");
                      if($city)
                      $tenantinfo["city_id"]=$city["id"];
                 }
                 $tid=$tenantLogic->insert($tenantinfo,TRUE);
                 if($user->figureurl_qq_2){
                     $image_url=  urlencode($user->figureurl_qq_2);
                     $this->runThread(Common::RewriteUrl("QQlogin", "savetouxiang")."?tid={$tid}&tx={$image_url}");
                   // $image=  $this->upload->save_image($user->figureurl_qq_2);
                }elseif($user->figureurl_qq_1){
                    $image_url=  urlencode($user->figureurl_qq_1);
                    $this->runThread(Common::RewriteUrl("QQlogin", "savetouxiang")."?tid={$tid}&tx={$image_url}");
                    //$image=  $this->upload->save_image($user->figureurl_qq_1);
                }
            }else{
                 $tenantinfo=array(
                    "last_login_ip"=>  Common::getIp(), 
                    "last_login_time"=>  time(),
                     "third_uid"=>$_SESSION["qq_openid"],
                  );
                  $tenantLogic->update($tenantinfo, "id={$exist["id"]}");
            }
            
            
            $tenant=$tenantLogic->get_one("*", "((user_name='{$_SESSION["qq_openid"]}' and password='{$password}') or third_uid='{$_SESSION["qq_openid"]}') and status=1");
             $_SESSION["tenant_info"]=$tenant;
             setcookie("tenant_info", serialize($tenant), time()+3600*24,"/");
        }
    }
   

    public function savetouxiang(){
        $tid=isset($_REQUEST["tid"])?intval($_REQUEST["tid"]):0;
        $touxiang=  isset($_REQUEST["tx"])?$_REQUEST["tx"]:"";
        if($touxiang&&$tid){
              $tenantLogic=  $this->load("tenant");
              $image=  $this->upload->save_image($touxiang);
              $data=array(
                  "image"=>$image
              );
              $tenantLogic->update($data,"id={$tid}");
              
        }
    }

   
    
    
    public function test(){

        //$this->upload->save_image("http://qzapp.qlogo.cn/qzapp/101230982/8DA49048691FFB2685DE48DC1425AAA7/30");
    }
}
